using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace AdvancedInspector
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public class RestrictAttribute : Attribute, IListAttribute, IRuntimeAttribute, IRuntimeAttribute<IList>
	{
		public delegate IList RestrictDelegate();

		private RestrictDisplay display;

		private int maxItemsPerRow = 6;

		private string methodName = string.Empty;

		private List<Delegate> delegates = new List<Delegate>();

		public RestrictDisplay Display
		{
			get
			{
				return display;
			}
			set
			{
				display = value;
			}
		}

		public int MaxItemsPerRow
		{
			get
			{
				return maxItemsPerRow;
			}
			set
			{
				maxItemsPerRow = value;
			}
		}

		public string MethodName
		{
			get
			{
				return methodName;
			}
		}

		public Type Template
		{
			get
			{
				return typeof(RestrictDelegate);
			}
		}

		public List<Delegate> Delegates
		{
			get
			{
				return delegates;
			}
			set
			{
				delegates = value;
			}
		}

		public RestrictAttribute(string methodName)
			: this(methodName, RestrictDisplay.DropDown)
		{
		}

		public RestrictAttribute(string methodName, RestrictDisplay display)
		{
			this.methodName = methodName;
			this.display = display;
		}

		public RestrictAttribute(Delegate method)
			: this(method, RestrictDisplay.DropDown)
		{
		}

		public RestrictAttribute(Delegate method, RestrictDisplay display)
		{
			delegates.Add(method);
			this.display = display;
		}

		public IList Invoke(int index)
		{
			if (delegates.Count == 0 || index >= delegates.Count)
			{
				return null;
			}
			try
			{
				return delegates[index].DynamicInvoke() as IList;
			}
			catch (Exception innerException)
			{
				if (innerException is TargetInvocationException)
				{
					innerException = ((TargetInvocationException)innerException).InnerException;
				}
				Debug.LogError(string.Format("Invoking a method to retrieve a Restrict attribute data failed. The exception was \"{0}\".", innerException.Message));
				return null;
			}
		}
	}
}
